# Maintainer: Konstantin Podsvirov <konstantin@podsvirov.pro>

_realname=cargo-generate
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.18.3
pkgrel=1
pkgdesc="Use pre-existing git repositories as templates (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://github.com/cargo-generate/cargo-generate"
license=('MIT' 'Apache')
makedepends=("${MINGW_PACKAGE_PREFIX}-rust"
             "${MINGW_PACKAGE_PREFIX}-mdbook")
options=('staticlibs' 'strip')
source=("$_realname-$pkgver.tar.gz::$url/archive/v$pkgver.tar.gz")
sha256sums=('e44e021dbc83cc862e4f52fce76ed6cfab0cf08d74505fe177bec048f981ac9b')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"

  cargo vendor \
    --locked \
    --versioned-dirs

  mkdir -p .cargo
  cat >> .cargo/config.toml <<END

[source.crates-io]
replace-with = "vendored-sources"

[source.vendored-sources]
directory = "vendor"
END


  sed -i -e 's/"cfg(all(target_arch = \\"\([^\\]\+\)\\", target_env = \\"gnu\\", target_abi = \\"llvm\\", not(windows_raw_dylib)))"/"\1-pc-windows-gnullvm"/g' \
    "vendor/windows-targets-0.48.0/Cargo.toml"
  sed -i -e 's/\("Cargo.toml":\)"[^"]\+"/\1"'"$(sha256sum "vendor/windows-targets-0.48.0/Cargo.toml" | cut -d' ' -f1)"'"/' \
    "vendor/windows-targets-0.48.0/.cargo-checksum.json"
}

build() {
  cd "${srcdir}"
  rm -rf "build-${MSYSTEM}" | true
  cp -r "${_realname}-${pkgver}" "build-${MSYSTEM}"
  msg "Cargo build for ${MSYSTEM}"
  cd "build-${MSYSTEM}"

  "${MINGW_PREFIX}/bin/cargo.exe" build \
    --release \
    --locked

  msg "Build documentation"
  cd guide

  "${MINGW_PREFIX}/bin/mdbook.exe" build
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  "${MINGW_PREFIX}/bin/cargo.exe" test \
    --release \
    --locked
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  install -Dm755 "target/release/${_realname}.exe" "${pkgdir}${MINGW_PREFIX}/bin/${_realname}.exe"
  install -d "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}"
  cp -a "guide/book" "${pkgdir}${MINGW_PREFIX}/share/doc/${_realname}/html"
  install -Dm644 "LICENSE-MIT" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE-MIT"
  install -Dm644 "LICENSE-APACHE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE-APACHE"
}

